from logs.set_logfile import logger
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from os import listdir, getcwd
from config import file_url_config, shanlian_config
from utils import file_utils, yzm_utils
from exception.scraping_exception import scraping_exception
from clean_data.shanlian_clean import clean_data


# 登陆闪链ERP
def login_shanlian(element_list):
    options = webdriver.ChromeOptions()

    options.add_experimental_option("prefs", {
        # D:\scraping\pythonProject\scraping
        "download.default_directory": file_url_config.download_selenium_excel_file_url,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing_for_trusted_sources_enabled": False,
        "download_restrictions": 0,
        "safebrowsing.enabled": False,
        "safebrowsing.disable_download_protection": True,
    })
    options.add_experimental_option('excludeSwitches',  ['enable-automation'])
    options.add_argument('disable-javascript')
    # options.add_argument("--user-data-dir=C:\\Users\\12630\\AppData\\Local\\Google\\Chrome\\User Data\\Default")
    driver = webdriver.Chrome(options)

    # 打开网址
    driver.get(shanlian_config.login_url)

    # 睡眠1s防止还没有打开完页面就直接点了页面
    sleep(4)
    # 0.点击欢迎登陆
    driver.find_element(By.XPATH, element_list[0]).click()
    # 1.点击ERP销存管理
    driver.find_element(By.XPATH, element_list[1]).click()
    count = 0
    while True:
        try:
            # 2.点击账号框 输入账号
            driver.find_element(By.XPATH, element_list[2]).clear()
            driver.find_element(By.XPATH, element_list[2]).send_keys(shanlian_config.username)
            # 3.点击密码框 输入账号
            driver.find_element(By.XPATH, element_list[3]).clear()
            driver.find_element(By.XPATH, element_list[3]).send_keys(shanlian_config.password)
            # 4.给验证码截图
            captcha_element = driver.find_element(By.XPATH, element_list[4])
            sleep(10)
            # 识别验证码
            captcha_text = yzm_utils.handle_yzm(driver, captcha_element)
            sleep(10)
            # 5.输入验证码
            driver.find_element(By.XPATH, element_list[5]).send_keys(captcha_text)
            sleep(5)
            # 6.点击登陆
            driver.find_element(By.XPATH, element_list[6]).click()
            sleep(5)
            count = count + 1
            logger.info(f"闪链第{count}次登陆尝试")
            if driver.current_url == 'http://szsl.yiweimenggdtc.com/wms/platform/index.jsp':
                break
            if count > 30:
                raise scraping_exception('闪链登陆失败!!')
        except scraping_exception as e:
            raise e
        except Exception as e:
            continue
    get_shanlian_data(driver, shanlian_config.get_data_element_list)


def get_shanlian_data(driver, element_list):
    # 获取没有下载之前的文件夹下的所有文件的列表
    file_list = listdir(file_url_config.download_selenium_excel_file_url)
    for i in range(0, len(element_list)):
        item = element_list[i]
        element_type = item['type']
        if 'XPATH' in item:
            xpath = item['XPATH']
            if element_type == 'click':
                driver.find_element(By.XPATH, xpath).click()
            elif element_type == 'send_keys':
                driver.find_element(By.XPATH, xpath).send_keys(item['value'])
        if 'switchFrame' in item:
            driver.switch_to.frame(item['switchFrame'])
        if 'sleep' in item:
            sleep(item['sleep'])
    # 用没下载之前的列表和下载之后的列表做对比 判断下载有没有完成
    files = file_utils.check_downfile(file_list)
    # 下载好之后 重命名文件保存起来
    file_utils.rename_file_title(
        source_dir=file_url_config.download_selenium_excel_file_url,
        destination_dir=file_url_config.download_excel_file_url,
        files=files,
        new_filename=shanlian_config.shanlian_excel_name
    )
    driver.switch_to.default_content()
    driver.quit()


def scraping():
    try:
        file_utils.delete_file(shanlian_config.shanlian_error_file_url)
        file_utils.delete_file(shanlian_config.selenium_excel_file_url)
        file_utils.delete_file(shanlian_config.excel_file_url)
        logger.info("开始获取闪链销售数据！")
        login_shanlian(shanlian_config.login_element_list)
        logger.info("闪链销售数据获取成功！")
        logger.info("闪链开始数据清洗！")
        clean_data()
        logger.info("数据清洗成功!")
    except Exception as e:
        logger.error("闪链销售数据导出报错!")
        logger.error(e)
        # 如果出错 就把创建的excel表格全部删除了
        file_utils.delete_file(shanlian_config.selenium_excel_file_url)
        file_utils.delete_file(shanlian_config.excel_file_url)
        file_utils.scraping_error(file_url=shanlian_config.shanlian_error_file_url, log_msg=e)


if __name__ == '__main__':
    # 今天的文件没有创建才可以调用这个方法
    # file_utils.create_today_dir()
    scraping()
